package vue;
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JWindow;
import javax.swing.ListModel;

import java.awt.Graphics;

import javax.swing.JLabel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.event.ListSelectionListener;

import modele.AlphaTrie;
import modele.Book;
import modele.Global;
import modele.SerializerPersonne;
import modele.DeSerializerPersonne;

public class  Fenetre {
	
	private DefaultListModel listModel = new DefaultListModel();
	private JList<Book> list = new JList(listModel);
	
	private DefaultListModel listModel1 = new DefaultListModel();
	private JList<Book> list1 = new JList(listModel1);
	
	private DefaultListModel listModel2 = new DefaultListModel();
	private JList<Book> list2 = new JList(listModel2);
	
	private static final int NB = 7;
	
	//Le nom des champs
	public static final String NAME="Name"; 
	public static final String SURNAME="Surname";
	public static final String PHONE="Phone";
	public static final String HOME_ADRESS="Home Adress";
	public static final String COMPANY_ADRESS="Company Adress";
	public static final String HOME_PAGE="Home Page";
	public static final String EMAIL="email";
	public static final String PHOTO="Photo";
	
	private String selectedTxt;
	private String selectedTxt1;
	private int compt=0;
	private boolean edite=false;
	
	private boolean arobase=false;
	
	private final static Fenetre FEN=new Fenetre();
	private final JFrame frame = new JFrame();
	
	private JPanel container = new JPanel();
	
	private JTextArea adress=new JTextArea();
	
	private	JScrollPane scrollPane= new JScrollPane();
	
	
	
    private ArrayList<String> Liste = new ArrayList<String>();
    
    private HashMap<Integer, String> contact = new HashMap<Integer, String>();
    
    private HashMap<Integer, String> contact_nom = new HashMap<Integer, String>();
    
    private HashMap<Integer, String> contact_nom_alpha = new HashMap<Integer, String>();
    
    private JTextField jtf_name = new JTextField();
	private JLabel label = new JLabel(NAME);
	
	private JTextField jtf_surname = new JTextField();
	private JLabel label1 = new JLabel(SURNAME);

	private JTextField jtf_phone = new JTextField();
	private JLabel label2 = new JLabel(PHONE);
	
	private JTextField jtf_home = new JTextField();
	private JLabel label3 = new JLabel(HOME_ADRESS);
	
	private JTextField jtf_compagny_adress = new JTextField();
	private JLabel label4 = new JLabel(COMPANY_ADRESS);
	
	private JTextField jtf_home_page = new JTextField();
	private JLabel label5 = new JLabel(HOME_PAGE);
	
	private JTextField jtf_email = new JTextField();
	private JLabel label6 = new JLabel(EMAIL);

	private JButton b = new JButton("OK");
	private JButton delete = new JButton("Delete");
	private JButton edit = new JButton("Edit");
	private JButton trierAlpha = new JButton("Alpha sort");
	private JButton trierDate = new JButton("Date sort");
	
	private JWindow d = new JWindow();
	
	private JPanel formulaire = new JPanel();
	private JPanel contactExistant = new JPanel();
	private JPanel contactExistant1 = new JPanel();
	private JPanel selection = new JPanel();
	private JPanel selection1 = new JPanel();
	
	

	private Fenetre() {
		
		Global.j=0;
		
		frame.setTitle("Adress Book");
		frame.setSize(900, 400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);

		frame.setLayout(new BorderLayout());
		
		Font police = new Font("Arial", Font.BOLD, 14);
		jtf_name.setFont(police);
		jtf_name.setPreferredSize(new Dimension(150, 30));
		jtf_name.setForeground(Color.BLUE);

		jtf_surname.setFont(police);
		jtf_surname.setPreferredSize(new Dimension(150, 30));
		jtf_surname.setForeground(Color.BLUE);

		jtf_phone.setFont(police);
		jtf_phone.setPreferredSize(new Dimension(150, 30));
		jtf_phone.setForeground(Color.BLUE);
		
		jtf_home.setFont(police);
		jtf_home.setPreferredSize(new Dimension(150, 30));
		jtf_home.setForeground(Color.BLUE);
		
		jtf_compagny_adress.setFont(police);
		jtf_compagny_adress.setPreferredSize(new Dimension(150, 30));
		jtf_compagny_adress.setForeground(Color.BLUE);
		
		jtf_home_page.setFont(police);
		jtf_home_page.setPreferredSize(new Dimension(150, 30));
		jtf_home_page.setForeground(Color.BLUE);
		
		jtf_email.setFont(police);
		jtf_email.setPreferredSize(new Dimension(150, 30));
		jtf_email.setForeground(Color.BLUE);
		
	}
		
		public void launch(){
		

		DeSerializerPersonne deserialize = DeSerializerPersonne.getDESER();
		Liste=deserialize.deser();
		
		for(int i = 0 ; i < Liste.size(); i++){
			
			String val= Liste.get(i);
		 	contact.put(i, val);
		 	System.out.println("attribut: " + val); 
		 	
		}
		
		
		
		formulaire.setLayout(new BoxLayout(formulaire, BoxLayout.PAGE_AXIS));
		formulaire.add(label);
		formulaire.add(jtf_name);

		formulaire.add(label1);
		formulaire.add(jtf_surname);

		formulaire.add(label2);
		formulaire.add(jtf_phone);
		
		formulaire.add(label3);
		formulaire.add(jtf_home);
		
		formulaire.add(label4);
		formulaire.add(jtf_compagny_adress);
		
		formulaire.add(label5);
		formulaire.add(jtf_home_page);
		
		formulaire.add(label6);
		formulaire.add(jtf_email);

		afficherAncien();
        
        list.addMouseListener((MouseListener) new MouseAdapter());
        
        list1.addMouseListener((MouseListener) new MouseAdapter());
        
        b.addActionListener((ActionListener) new BoutonListener());
		delete.addActionListener((ActionListener) new BoutonListener());
		edit.addActionListener((ActionListener) new BoutonListener());
		
		trierAlpha.addActionListener((ActionListener) new BoutonListener());
		trierDate.addActionListener((ActionListener) new BoutonListener());
		
		frame.addWindowListener(new MyWindowListener());
        
		formulaire.add(b);
		selection.add(trierDate);
		selection.add(trierAlpha);
		selection.add(delete);
		selection.add(edit);
		
		selection.setBackground(Color.CYAN);
		
		formulaire.setBackground(Color.CYAN);
		
		frame.getContentPane().add(selection, BorderLayout.NORTH);
		

		scrollPane.getViewport().add( contactExistant );
		frame.getContentPane().add(scrollPane, BorderLayout.WEST);
		
		frame.getContentPane().add(formulaire, BorderLayout.EAST);
		
		frame.setVisible(true);
	}
	
	
	

public void afficherAncien(){
	
	int j=0;
	String maValeur = null;
	boolean test;
	
	listModel.removeAllElements();
	contactExistant.removeAll();
	
	
    for(int i = 0; i <contact.size(); i++){
    	
    	
    	
    	if(i%NB==0) {maValeur = contact.get(i);
    	
    	contact_nom.put(j, maValeur);
    	j++;
    	}
    	System.out.println("icicici : "+contact.get(i));
    	
    	
		
        
    }
    
for(int i = 0; i <contact_nom.size(); i++){
    	
    	maValeur = contact_nom.get(i);
    	
    	
    	
	 	
    	listModel.addElement(contact_nom.get(i));
		contactExistant.add(list);
		
		System.out.println(maValeur);
		
   
    }

}

	class BoutonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int ajout=0;
			if(e.getSource()==b){
				
				if(edite==true){
					
					Book changer= new Book(contact, Liste, jtf_name.getText(),jtf_surname.getText(),jtf_phone.getText(), jtf_home.getText(), jtf_compagny_adress.getText(), jtf_home_page.getText(),jtf_email.getText());
					
					changer.Edit(compt);
					
					Liste=changer.getArr();
					contact=changer.getHash();
					
					afficherAncien();
					edite=false;
					
				}
				
				else{
					
			Book nouveau= new Book(contact, Liste, jtf_name.getText(),jtf_surname.getText(),jtf_phone.getText(), jtf_home.getText(), jtf_compagny_adress.getText(), jtf_home_page.getText(),jtf_email.getText());
					
			nouveau.newOne();
			
			Liste=nouveau.getArr();
			contact=nouveau.getHash();
					
			afficherAncien();
			
			frame.setVisible(true);
			
			
			
				}
		
			jtf_name.setText("");
			jtf_surname.setText("");
			jtf_phone.setText("");
			jtf_home.setText("");
			jtf_compagny_adress.setText("");
			jtf_home_page.setText("");
			jtf_email.setText("");
			
			}
			
			else if(e.getSource()==delete){
				int div=0;
				System.out.println("you trie the delete button");

				
				Book effacer = new Book(contact, Liste, null, null, null, null, null, null, null );
				
				effacer.Delete(compt);
				
				
				Liste=effacer.getArr();
				contact=effacer.getHash();
				
				contact_nom.remove(compt/7);
				
				afficherAncien();
				
				listModel.removeElement(selectedTxt);
				listModel1.clear();
				
			}
			
			else if(e.getSource()==edit){
				System.out.println("you trie the edit button");
				
				jtf_name.setText(contact.get(compt));
				jtf_surname.setText(contact.get(compt+1));
				jtf_phone.setText(contact.get(compt+2));
				jtf_home.setText(contact.get(compt+3));
				jtf_compagny_adress.setText(contact.get(compt+4));
				jtf_home_page.setText(contact.get(compt+5));
				jtf_email.setText(contact.get(compt+6));
				
				edite=true;
				
				
			}
			
			else if(e.getSource()==trierAlpha){
				
				listModel.removeAllElements();
				contactExistant.removeAll();
				
				AlphaTrie trier = new AlphaTrie(contact_nom);

				contact_nom_alpha=trier.trie();
				
				String maValeur=null;
				
				for(int i = 0; i <contact_nom_alpha.size(); i++){
			    	
			    	maValeur = contact_nom_alpha.get(i);
			    
			    	listModel.addElement(contact_nom_alpha.get(i));
					contactExistant.add(list);
					
					System.out.println(maValeur);
					
			   
			    }
				
				scrollPane.getViewport().add( contactExistant );
				frame.getContentPane().add(scrollPane, BorderLayout.WEST);	
				frame.setVisible(true);
				
				
			}
			
			else if(e.getSource()==trierDate){
				
				listModel.removeAllElements();
				contactExistant.removeAll();
				
				
				afficherAncien();
				scrollPane.getViewport().add( contactExistant );
				frame.getContentPane().add(scrollPane, BorderLayout.WEST);	
				frame.setVisible(true);
				
				
			}

		}
	}
	
	
	
	class MouseAdapter implements MouseListener {
		
		@Override
		public void mouseClicked(MouseEvent arg0) {
			//System.out.println("Mouse Clicked");
			
			//list.getSelectedValue().toString();
			//list.getSelectedValue().getName();
			
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			
			//System.out.println("Mouse Entered");
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			
			//System.out.println("salam alikoum");
			
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			
			//System.out.println("Mouse Pressed");
			
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			
			if(e.getSource()==list){
			
			listModel1.clear();
			
			JList jta = (JList) e.getSource();
					
			 selectedTxt = (String) jta.getSelectedValue();
			
			
			for (int i=0; i<contact.size();i++){
				
				
				if(contact.get(i)==selectedTxt){
					System.out.println(contact.get(selectedTxt));
					
					compt=i;
					System.out.println("le code est "+compt);
					
				}
			}
			
			String val=null;
			for (int i=compt; i<compt+NB;i++){
				
				if(i==(compt+0))val=NAME;
				if(i==(compt+1))val=SURNAME;
				if(i==(compt+2))val=PHONE;
				if(i==(compt+3))val=HOME_ADRESS;
				if(i==(compt+4))val=COMPANY_ADRESS;
				if(i==(compt+5))val=HOME_PAGE;
				if(i==(compt+6))val=EMAIL;
				
				listModel1.addElement(val+ " : "+contact.get(i));
				selection1.add(list1);
				
			}
			selection1.setBackground(Color.green);
			selection1.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
			frame.getContentPane().add(selection1, BorderLayout.CENTER);
			
			frame.setVisible(true);
			
			System.out.println(selectedTxt);
			
			}
			
			else if(e.getSource()==list1){
				
				
				System.out.println("je suis au milieu !!!!");
				
				 JList jta = (JList) e.getSource();
				 
				 selectedTxt1 = (String) jta.getSelectedValue();
				 
				 if(selectedTxt1.contains("@"))arobase=true;
				 
				 if(selectedTxt1.contains(".")&&arobase==false){
					 
					 String site_web=null;
					 site_web=selectedTxt1.substring(12, selectedTxt1.length());
					 System.out.println("la home page est "+site_web);
					 
					 
					 
					 if(Desktop.isDesktopSupported()){
							if(Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)){
								URI uri;
								try {
									uri = new URI("http://"+site_web);
									Desktop.getDesktop().browse(uri);
								} catch (URISyntaxException arg0) {
									arg0.printStackTrace();
								} catch (IOException arg0) {
									arg0.printStackTrace();
								}
							}
						}
					 
		 
				 }
				 
				 else if(arobase==true){
					
					 String mail=null;
					 mail=selectedTxt1.substring(8, selectedTxt1.length());
					 System.out.println("le mail est "+mail);
					 
					 Desktop desktop = Desktop.getDesktop();
					 String message = "mailto:"+mail;
					 URI uri = URI.create(message);
					 try {
						desktop.mail(uri);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					 
					 arobase=false;
					 
					 
				 }
				 
				 				
			}
			
		}
		
	}
	
	class MyWindowListener implements WindowListener {
        public void windowActivated (WindowEvent e) {}
        public void windowClosed (WindowEvent e) {System.exit(0);}
        public void windowClosing (WindowEvent e) {
         
        	
        	
        	SerializerPersonne Oldserialize = SerializerPersonne.getSER();
			Oldserialize.serialOld(contact);
			Oldserialize.serial();
            ((Frame)e.getSource()).dispose();
            }
        public void windowDeactivated (WindowEvent e) {}
        public void windowDeiconified (WindowEvent e) {}
        public void windowIconified (WindowEvent e) {}
        public void windowOpened (WindowEvent e) {}
        }
	
public static Fenetre getFen(){
		
		return FEN;
		
	}
	
	
}
